package com.benjaminwan.read.free.utils

import android.text.Html
import android.text.TextUtils
import com.benjaminwan.read.free.common.BaseUrl
import org.jsoup.Jsoup
import org.jsoup.nodes.Document
import org.jsoup.safety.Whitelist
import java.util.regex.Pattern

object HiUtils {
    private const val AVATAR_BASE = "000000000"
    const val AvatarPath = "uc_server/data/avatar/"
    const val AvatarBaseUrl: String = BaseUrl + AvatarPath
    const val AvatarSuffix = "_avatar_middle.jpg"
    private var mWhitelist: Whitelist? = null
    const val URL_REGEX =
        "[(http(s)?):\\/\\/(www\\.)?a-zA-Z0-9@:%._\\+~#=]{2,256}\\.[a-z]{2,6}\\b([-a-zA-Z0-9@:%_\\+.~#?&//=]*)"
    lateinit var URL_PATTERN: Pattern
    const val CookieDomain = "hi-pda.com"
    const val ForumImagePattern: String = CookieDomain + "/forum/images/"
    const val SmiliesPattern: String = CookieDomain + "/forum/images/smilies/"

    init {
        URL_PATTERN = Pattern.compile(
            URL_REGEX
        )
    }

    fun fromHtmlAndStrip(s: String?): CharSequence {
        return Html.fromHtml(s, Html.FROM_HTML_MODE_LEGACY).toString()
            .replace(160.toChar(), 32.toChar())
            .replace(65532.toChar(), 32.toChar())
    }

    fun trim(text: String): String {
        return text.replace(160.toChar().toString(), " ").trim()
    }

    fun getMiddleString(
        source: String,
        start: String,
        end: String
    ): String {
        var start_idx = source.indexOf(start)
        if (start_idx == -1) return ""
        start_idx += start.length
        var end_idx: Int
        if (TextUtils.isEmpty(end)) {
            end_idx = source.length
        } else {
            end_idx = source.indexOf(end!!, start_idx)
            if (end_idx == -1) {
                end_idx = source.length
            }
        }
        return if (end_idx == -1 || end_idx <= start_idx) {
            ""
        } else source.substring(start_idx, end_idx)
    }

    fun getIntFromString(s: String): Int {
        val tmp = s.replace("[^\\d]".toRegex(), "")
        return if (!TextUtils.isEmpty(tmp) && TextUtils.isDigitsOnly(tmp)) {
            tmp.toIntOrNull() ?: 0
        } else {
            0
        }
    }

    fun parseInt(s: String?): Int {
        return s?.toIntOrNull() ?: 0
    }

    fun nullToText(text: CharSequence): String {
        return if (TextUtils.isEmpty(text)) {
            ""
        } else text.toString()
    }

    fun parseSizeText(s: String): Long {
        //708 Bytes
        //100.1 KB
        //2.22 MB
        var sizeText = s.trim().toUpperCase()
        try {
            if (sizeText.endsWith("KB")) {
                return Math.round(
                    sizeText.replace("KB", "").trim { it <= ' ' }.toDouble() * 1024
                )
            } else if (sizeText.endsWith("MB")) {
                return Math.round(
                    sizeText.replace("MB", "").trim { it <= ' ' }.toDouble() * 1024 * 1024
                )
            } else if (sizeText.endsWith("BYTES")) {
                return sizeText.replace("BYTES", "").trim { it <= ' ' }.toLong()
            }
        } catch (ignored: Exception) {
        }
        return -1
    }

    fun getAvatarUrlByUid(uid: String): String {
        if (TextUtils.isEmpty(uid)
            || uid.length > AVATAR_BASE.length
            || !TextUtils.isDigitsOnly(uid)
        ) return ""
        val fullUid: String = AVATAR_BASE.substring(
            0,
            AVATAR_BASE.length - uid.length
        ) + uid
        return (AvatarBaseUrl
                + fullUid.substring(0, 3) + "/"
                + fullUid.substring(3, 5) + "/"
                + fullUid.substring(5, 7) + "/"
                + fullUid.substring(7, 9) + AvatarSuffix)
    }

    fun isValidId(id: String?): Boolean {
        return !TextUtils.isEmpty(id) && parseInt(
            id
        ) > 0
    }

    fun clean(html: String?): String? {
        if (mWhitelist == null) {
            mWhitelist = Whitelist()
            mWhitelist?.addTags(
                "a",
                "br", "p",
                "b", "i", "strike", "strong", "u",
                "font"
            )
                ?.addAttributes("a", "href")
                ?.addAttributes("font", "color")
                ?.addProtocols("a", "href", "http", "https")
        }
        return Jsoup.clean(
            html,
            "",
            mWhitelist!!,
            Document.OutputSettings().prettyPrint(false)
        )
    }

    fun removeLeadingBr(input: String): String {
        return if (input.startsWith("<br>")) {
            val ret = input.replaceFirst("<br>", "")
            removeLeadingBr(ret)
        } else {
            input
        }
    }
}